import React, {useEffect, useMemo, useState} from 'react';
import {Table, Space, Button, message, Input} from 'antd';
import {
  postsType,
  posts,
  updatePosts,
  searchPosts,
  pushPostsType,
  searchPostsType,
  createPost,
  deletePost
} from '../../api/posts';
import {formatDateTime} from '../../utils/time-format';
import CollectionCreateForm from './component/Madol';
import moment from 'moment';
import {PostsTypeMap, PostTpypeRollbackMap} from '../../api/typeMap';
const {Search} = Input;
const {Column} = Table;
import './style.scss';

const initRowData = {
  id: 0,
  thumb_url: '',
  content: '',
  type: 0,
  create_time: new Date(),
  update_time: new Date(),
  title: '',
  author: ''
};

const initFormData = {
  thumb_url: '',
  content: '',
  type: 0,
  create_time: new Date(),
  update_time: new Date(),
  title: '',
  author: '张三'
};

const initSearchForm = {
  title: '',
  author: '',
  id: 0,
  thumb_url: ''
};

export default function Posts() {
  const [data, setData] = useState({list: []});
  //  使用 useEffect请求初始数据

  useEffect(() => {
    posts().then(res => {
      res.list.map(
        (item: {create_time: string | Date; update_time: string | Date}) => {
          item.create_time = formatDateTime(item.create_time);
          item.update_time = formatDateTime(item.update_time);
        }
      );
      setData({list: res.list});
    });
  }, []);

  const [visible, setVisible] = useState(false);
  const [rowData, setRowData] = useState(initRowData);
  const [initForm, setInitFrom] = useState(initFormData);
  const [searchForm, setSearchForm] = useState(initSearchForm);

  // 点击编辑事件
  const editEvent = (record: any) => {
    // 不能直接修改源数据 需要浅拷贝一次
    function shallowClone(record: any) {
      let temp: any = {};
      for (let i in record) {
        temp[i] = record[i];
      }
      temp.type = PostsTypeMap.get(temp.type);
      temp.create_time = moment(temp.create_time, 'YYYY-MM-DD HH:mm:ss');
      temp.update_time = moment(temp.update_time, 'YYYY-MM-DD HH:mm:ss');
      return temp;
    }
    let obj = shallowClone(record);
    setRowData(obj);
    setVisible(true);
  };

  const changeVisible = (status: boolean) => {
    setVisible(status);
  };

  // 搜索
  const onSearch = (value: string) => {
    if (value === '') {
      posts().then(res => {
        res.list.map(
          (item: {create_time: string | Date; update_time: string | Date}) => {
            item.create_time = formatDateTime(item.create_time)!;
            item.update_time = formatDateTime(item.update_time)!;
          }
        );
        setData({list: res.list});
      });
    } else {
      searchPosts(value).then(data => {
        data.map(
          (item: {create_time: string | Date; update_time: string | Date}) => {
            item.create_time = formatDateTime(item.create_time);
            item.update_time = formatDateTime(item.update_time);
          }
        );
        setData({list: data});
      });
    }
  };

  const onSearchFrom = (values: any) => {
    console.log(values);
    console.log();
  };

  // 刷新数据
  const reRequstList = function () {
    posts().then(res => {
      res.list.map(
        (item: {create_time: string | Date; update_time: string | Date}) => {
          item.create_time = formatDateTime(item.create_time);
          item.update_time = formatDateTime(item.update_time);
        }
      );
      setData({list: res.list});
    });
  };

  // 保存传递给后台
  const onSaveData = async (values: postsType) => {
    console.log(values);
    // 转换成Date 对象
    values.type = PostTpypeRollbackMap.get(values.type)!;
    values.create_time = new Date(
      moment(values?.create_time).format('YYYY-MM-DD HH:mm:ss')
    );
    values.update_time = new Date(
      moment(values?.update_time).format('YYYY-MM-DD HH:mm:ss')
    );
    changeVisible(false);
    // 文章的id 由后台去定义 这样直接发请求
    if (!!values.id) {
      // 修改数据
      updatePosts(values).then(data => {
        // 成功的时候刷新一次
        if (data.statusCode === 200) {
          reRequstList();
          message.success('更新成功');
        } else {
          message.error('更新失败');
        }
      });
    } else {
      // 创建一篇文章
      createPost(values).then(data => {
        reRequstList();
        message.success('添加成功');
      });
    }
  };

  // 删除
  const DeleteEvent = async (id: number) => {
    console.log(id);
    deletePost(id).then(res => {
      console.log(res);
      reRequstList();
      message.success('删除成功');
    });
  };

  return (
    <div>
      <div className="search-header">
        请输入标题：
        <Search
          placeholder="请输入文章标题"
          onSearch={onSearch}
          style={{width: 320, marginBottom: '10px'}}
          enterButton
        />
        {/*
        这里用成 from 表单去修改更加合理一些
        */}
        <Input.Group compact className="group">
          <div style={{marginLeft: '20px'}}>
            {' '}
            <span>请输入id：</span>
            <Input style={{width: 220, marginBottom: '10px'}} defaultValue="" />
          </div>
          <div style={{marginLeft: '20px'}}>
            <span> 请输入链接：</span>
            <Input style={{width: 160, marginBottom: '10px'}} defaultValue="" />
          </div>
          <div style={{marginLeft: '20px'}}>
            <span> 请输入标题：</span>
            <Input style={{width: 160, marginBottom: '10px'}} defaultValue="" />
          </div>
          <div style={{marginLeft: '20px'}}>
            <span> 请输入作者：</span>
            <Input style={{width: 160, marginBottom: '10px'}} defaultValue="" />
          </div>
          <Button
            type="primary"
            onClick={e => {
              onSearchFrom(searchForm);
            }}
            style={{width: 60, marginBottom: '10px', marginLeft: '10px'}}
          >
            搜索
          </Button>
        </Input.Group>
        <Button
          type="primary"
          onClick={event => {
            editEvent(initForm);
          }}
        >
          ADD Post
        </Button>
      </div>
      <Table size="small" dataSource={data.list} rowKey={'id'}>
        <Column title="id" dataIndex="id" />
        <Column title="title" dataIndex="title" />
        <Column
          title="内容"
          key="content"
          render={(text, record: postsType) => (
            <span dangerouslySetInnerHTML={{__html: record.content}}></span>
          )}
        />
        <Column title="链接" dataIndex="thumb_url" />
        <Column title="作者" dataIndex="author" />
        <Column
          title="类别"
          key="type"
          render={(text, record: postsType) => (
            <span>
              {/* {record.type} // 渲染出原始数据 */}
              {PostsTypeMap.get(record.type)}
            </span>
          )}
        />
        <Column title="创建时间" dataIndex="create_time" />
        <Column title="更新时间" dataIndex="update_time" />
        <Column
          title="Action"
          key="action"
          render={(text, record: pushPostsType) => (
            <Space size="middle">
              <Button
                type="primary"
                onClick={event => {
                  event.stopPropagation(), editEvent(record);
                }}
                block
              >
                update
              </Button>
              <Button
                danger
                onClick={event => {
                  event.stopPropagation(), DeleteEvent(record.id);
                }}
              >
                Delete
              </Button>
            </Space>
          )}
        />
      </Table>
      <CollectionCreateForm
        visible={visible}
        onCancel={() => {
          changeVisible(false);
        }}
        currentDetailData={rowData}
        submitMap={onSaveData}
      />
    </div>
  );
}
